package com.webmagic;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

public class FirstNewsSpider implements PageProcessor {


    // 抓取网站的相关配置，包括编码、抓取间隔、重试次数等
    private Site site = Site.me().setRetryTimes(3).setSleepTime(100);
    @Override
    public Site getSite() {
        return site;
    }
    @Override
    public void process(Page page) {
        // 文章页，匹配 https://voice.hupu.com/nba/七位数字.html
        // http://38.103.161.228/forum/thread-10750386-1-1.html
        // http://38.103.161.228/forum/thread-10750384-1-1.html
        // http://38.103.161.228/forum/thread-[0-9]{8}-1-1.html
        // https://voice\.hupu\.com/nba/[0-9]{7}\.html
        // http://38.103.161.228/forum/thread-[0-9]{8}-1-1.html
        if (page.getUrl().regex("http://38.103.161.228/forum/thread-[0-9]{8}-1-1.html").match()) {
            page.putField("Title", page.getHtml().xpath("/html/body/div[4]/div[1]/form/div/table/tbody/tr[1]/td[2]/div[3]/h2/text()").toString());
            page.putField("Content",
                    page.getHtml().xpath("/html/body/div[4]/div[1]/form/div/table/tbody/tr[1]/td[2]/div[3]/div[4]/dl/dt/a[2]/text()").all().toString());
        }
        // 列表页
        else {
            // 文章url
            page.addTargetRequests(
                    page.getHtml().xpath("/html/body/div[4]/div[1]/div[7]/form/table[5]/tbody[2]/tr/th/span[1]/a/@href").all());
            // 翻页url
            page.addTargetRequests(
                    page.getHtml().xpath("/html/body/div[4]/div[1]/div[8]/div/a/@href").all());
        }
    }

    public static void main(String[] args) {
        // 欧美  http://38.103.161.228/forum/forum-229-1.html
        // 网页  http://38.103.161.228/forum/thread-10750386-1-1.html
        Spider.create(new FirstNewsSpider()).addUrl("http://38.103.161.228/forum/forum-229-1.html").addPipeline(new MysqlPipeline())
                .thread(3).run();
    }
}
